import axios from "axios"
import router from "../router/index"
import store from "../store/index"

const service = axios.create({
    baseURL: "http://127.0.0.1:8080",
    timeout: 30 * 1000
})

service.interceptors.request.use((req) => {
    let user = store.state.user || "{}"
    req.headers['token'] = user.token;
    return req
})

service.interceptors.response.use(response => {
    let res = response.data

    if (typeof res === "string") {
        res = res ? JSON.parse(res) : res
    }

    if (res.code === 401) {
        router.push("/")
    }

    return res
}, error => {
    console.log("response error:" + error)
    return Promise.reject(error)
})

function request(options) {
    options.method = options.method || "get"
    if (options.method.toLowerCase() == "get") {
        options.params = options.data
    }
    return service(options)
}

export default request